#include "pagetable.h"

#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/mm_types.h>
#include <asm/pgtable.h>

#include <linux/ptdump.h>

// CRS List: https://five-embeddev.com/quickref/csrs.html

typedef struct csr_lists
{
    int address;
    const char* name;
} csr_lists;

csr_lists list[] = 
{
    {0xc00, "CYCLE"},
    {0x0180, "SATP"}
};

#define CSRR_READ(v, csr)                           \
/* CSRR_READ(v, csr):
 * csr: MUST be a compile time integer 12-bit constant (0-4095)
 */                                             \
__asm__ __volatile__ ("csrr %0, %1"             \
              : "=r" (v)                        \
              : "n" (csr)                       \
              : /* clobbers: none */ );

void test_page_table_lookup() {
    unsigned long long satp = 0, kpgd = 0, kpgd1 = 0;
    CSRR_READ(satp, 0x0180);
    kpgd = satp & (((unsigned long long)1 << 44) - 1);
    printk(KERN_ALERT "[kgpd] swapper_pg_dir satp=0x%lx va=0x%lx pa=0x%lx\n", satp, kpgd, __pa(kpgd));

    printk(KERN_ALERT "[kgpd] init_mm.pgd=0x%lx pa=0x%lx\n", init_mm.pgd, __pa(init_mm.pgd));

    printk(KERN_ALERT "[kgpd] kernel_map.va_pa_offset=0x%lx virt_offset=0x%lx va_kernel_pa_offset=0x%lx phys_addr=0x%lx virt_addr=0x%lx\n",
        (unsigned long)kernel_map.va_pa_offset, (unsigned long)kernel_map.virt_offset,
        (unsigned long)kernel_map.va_kernel_pa_offset, (unsigned long)kernel_map.phys_addr, (unsigned long)kernel_map.virt_addr);

    printk(KERN_ALERT "[kgpd] init_mm.pgd=0x%lx pa=0x%lx\n", (unsigned long)init_mm.pgd - (unsigned long)kernel_map.virt_offset);

    printk(KERN_ALERT "[kgpd] swapper_pg_dir data=0x%lx\n", *(unsigned long long*)kpgd);
}